<template>
  <div class="user-management-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-inputs">
        <el-input
          v-model="search1"
          placeholder="请输入用户名查询"
          class="search-input"
          clearable
        />
        <el-input
          v-model="search2"
          placeholder="请输入邮箱查询"
          class="search-input"
          clearable
        />
        <div class="search-buttons">
          <el-button type="primary" @click="getUserList()" class="search-button">
            <el-icon><Search /></el-icon>
            <span>搜索</span>
          </el-button>
          <el-button @click="resetSearch()" class="search-button">
            <el-icon><Refresh /></el-icon>
            <span>重置</span>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="success" @click="userAdd = true" class="action-button">
        <el-icon><Plus /></el-icon>
        <span>新增用户</span>
      </el-button>
      <el-button type="danger" plain class="action-button">
        <el-icon><Delete /></el-icon>
        <span>批量删除</span>
      </el-button>
    </div>

    <!-- 新增用户对话框 -->
    <el-dialog v-model="userAdd" title="新增用户" width="500px">
      <el-form :model="form" label-position="top">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="头像URL" :label-width="formLabelWidth">
          <el-input v-model="form.userPic" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userAdd = false">取消</el-button>
          <el-button type="primary" @click="userAdd1">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户表格 -->
    <div class="table-container">
      <el-table
        :data="users"
        stripe
        border
        style="width: 100%"
        :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column label="头像" width="100" align="center">
          <template #default="scope">
            <el-avatar :src="scope.row.userPic" />
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="phone" label="电话" min-width="130" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button
              @click="editUser(scope.row)"
              type="primary"
              size="small"
              plain
            >
              编辑
            </el-button>
            <el-button
              @click="deleteUser(scope.row.id)"
              type="danger"
              size="small"
              plain
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editUser1" title="编辑用户信息" width="500px">
      <el-form :model="form1" label-position="top">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form1.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth">
          <el-input v-model="form1.nickname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="头像URL" :label-width="formLabelWidth">
          <el-input v-model="form1.userPic" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editUser1 = false">取消</el-button>
          <el-button type="primary" @click="editUserConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[6, 9, 12, 15]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>


<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  height: 90%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
}

.search-inputs {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 240px;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

.search-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;

}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-border: 1px solid #ebeef5;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-button {
  border-radius: 4px;
}
</style>

<script setup lang="ts">
import {ref, onMounted, reactive} from 'vue';
import request from "@/api/request";
import {ElMessage, ElTable} from 'element-plus'
interface User {
  id: number | null;
  userPic: string;
  username: string;
  nickname: string;
  phone: string;
  email: string;
  creatTime: any;
}

const pageNum = ref(1); // 从1开始
const pageSize = ref(6);
const totalUsers = ref(0); // 用于存储总用户数

const users = ref<User[]>([]);
const search1 = ref('');
const search2 = ref('');

const userAdd = ref(false)
const editUser1 = ref(false)
const formLabelWidth = '120px'
const form = reactive({
  username: '',
  userPic:'',
})
const form1 = reactive<{
  id: number | null; // 允许 id 为 number 或 null
  username: string;
  userPic: string;
  nickname: string;
}>({
  id: null,
  username: '',
  userPic: '',
  nickname: '',
});
// 获取用户列表
const getUserList = () => {
  request.get('/admin/userList', {
    params: {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      username: search1.value,
      email: search2.value,
    },
  }).then((res: any) => {
    users.value = res.data.items; // 假设返回的数据结构是这样的
    totalUsers.value = res.data.total; // 假设返回的总数在这里
    if (res.data.total.length === 0){
      console.log('不存在该用户')
      ElMessage.warning('不存在该用户');
    }
  }).catch((error: any) => {
    console.error('获取用户失败:', error); // 处理错误
  });
};
//新增用户
const userAdd1 = () => {
  request.post('/admin/addUser', {
    username: form.username,
    userPic: form.userPic,
  }).then((res: any) => {
    console.log('新增用户成功:', res);
    // 这里可以添加成功后的逻辑
    userAdd.value = false;
    ElMessage.success('新增用户成功');
  }).catch((error: any) => {
    console.error('新增用户失败:', error); // 处理错误
    ElMessage.error(error);
  });
};

//编辑用户
const editUser = (user: User) => {
  console.log('编辑用户:', user);
  form1.id = user.id; // 设置用户 ID
  form1.username = user.username;
  form1.nickname = user.nickname;
  form1.userPic = user.userPic;
  editUser1.value = true;
};
const editUserConfirm = () => {
  request.patch('/admin/updateUser', {
    id:form1.id,
    username: form1.username,
    userPic: form1.userPic,
    nickname: form1.nickname,
  }).then((res: any) => {
    // 更新用户列表
    getUserList();
    editUser1.value = false; // 关闭编辑对话框
    ElMessage.success('编辑用户成功');
  }).catch((error: any) => {
    console.error('编辑用户失败:', error); // 处理错误
    console.log(form1.id)
    ElMessage.error('编辑用户失败');
  });
};
const deleteUser = (userId: number) => {
  console.log('删除用户 ID:', userId);
  // 这里可以添加删除用户的逻辑
  users.value = users.value.filter(user => user.id !== userId);
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageSize.value = val; // 更新页面大小
  getUserList(); // 更新用户列表
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  pageNum.value = val; // 更新当前页码
  getUserList(); // 更新用户列表
};
//重置搜索框
const resetSearch = () => {
  search1.value = ''
  search2.value = ''
  getUserList()
};

onMounted(() => {
  getUserList(); // 组件挂载时获取用户列表
});
</script>